package com.ruoyi.web.controller.ucenter.api;


import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ruoyi.activity.service.IActivityService;
import com.ruoyi.activity.service.IApplyService;
import com.ruoyi.activity.service.IContestService;
import com.ruoyi.blog.service.BlogService;
import com.ruoyi.common.annotation.Check;
import com.ruoyi.model.activity.Activity;
import com.ruoyi.model.apply.Apply;
import com.ruoyi.model.blog.Blog;
import com.ruoyi.model.contest.Contest;
import com.ruoyi.model.message.UserMessage;
import com.ruoyi.model.user.UserInfo;
import com.ruoyi.model.user.UserInformation;
import com.ruoyi.model.user.dto.UserInfoDto;
import com.ruoyi.model.auth.AuthContextHolder;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.model.user.form.UserInfoForm;
import com.ruoyi.ucenter.service.IUserInfoService;
import com.ruoyi.ucenter.service.IUserMessageService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author : 张怀秋
 **/
@Api(tags = "个人用户信息")
@RestController
@RequestMapping("/api/u-center")
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class UserInfoApiController extends BaseController {

    private final IUserInfoService userInfoService;
    private final BlogService blogService;
    private final IApplyService applyService;
    private final IActivityService activityService;
    private final IContestService contestService;
    private final IUserMessageService userMessageService;


    @Check
    @ApiOperation(value = "用户添加获奖荣誉")
    @PutMapping("/save/information")
    public AjaxResult saveInformation(@RequestBody UserInformation information) {
        return AjaxResult.success(userInfoService.saveInformation(information));
    }

    @Check
    @ApiOperation("首页获取未读取邮件的数量")
    @GetMapping("/getHomeMessageNotRead")
    public AjaxResult getHomeMessageNotRead() {
        String userId = AuthContextHolder.getUserId();
        Long count = userMessageService.count(Wrappers.<UserMessage>lambdaQuery()
                .eq(UserMessage::getUserId, userId)
                .eq(UserMessage::getStatus, 1));
        return AjaxResult.success(count);
    }

    @Check
    @ApiOperation("查询当前用户的邮件，以及没读取的邮件数量")
    @GetMapping("/get-message-list")
    public AjaxResult getMessageList() {
        Map<String, Object> map = new HashMap<>();
        String userId = AuthContextHolder.getUserId();
        List<UserMessage> list = userMessageService.list(Wrappers.<UserMessage>lambdaQuery()
                .eq(UserMessage::getUserId, userId)
                .orderByDesc(UserMessage::getStatus) // 排序规则1：按照状态（status）降序排列
                .orderByDesc(UserMessage::getSendTime) // 排序规则2：按照发送时间（sendTime）
                // 降序排列
        );
        //当前人员的全部邮件
        map.put("messageList", list);
        //当前人员的围未读邮件
        map.put("notReadNum",
                list.stream().filter(item -> item.getStatus() == 1).count()
        );
        return AjaxResult.success(map);
    }

    @Check
    @ApiOperation("删除消息")
    @DeleteMapping("/remove-message/{id}")
    public AjaxResult removeMessageById(@ApiParam("消息中心") @PathVariable Long id) {
        return AjaxResult.success(userMessageService.removeById(id));
    }

    @Check
    @ApiOperation("修改当前邮箱状态为已读写")
    @PostMapping("/updateMessageStatus/{msgId}")
    public AjaxResult updateMessageStatus(@ApiParam("msgId") @PathVariable String msgId) {
        UserMessage userMessage = this.userMessageService.selectUserMessageById(msgId);
        userMessage.setStatus(0);
        boolean result = this.userMessageService.updateById(userMessage);
        return toAjax(result);
    }

    @Check
    @ApiOperation(value = "用户查询获奖荣誉列表")
    @GetMapping("/information/list")
    public AjaxResult getInformationList() {
        return AjaxResult.success(userInfoService.getInformation());
    }

    @Check
    @ApiOperation(value = "用户查询获奖荣誉详细")
    @GetMapping("/information/{id}")
    public AjaxResult getInformation(@PathVariable String id) {
        return AjaxResult.success(userInfoService.getInformationById(id));
    }

    @Check
    @ApiOperation(value = "获取用户信息", notes = "待完善")
    @GetMapping("/getLoginUserInfo")
    public AjaxResult getLoginUserInfo() {
        UserInfo userInfo = AuthContextHolder.getUserInfo();
        return AjaxResult.success(userInfoService.selectUserInfo(userInfo));
    }

    @Check
    @ApiOperation(value = "编辑个人基本信息", notes = "暂时只考虑了基本信息修改")
    @PostMapping("/edit")
    public AjaxResult editUserInfo(@RequestBody UserInfoForm userInfoForm) {
        String userId = AuthContextHolder.getUserId();
        return toAjax(userInfoService.editUserInfoById(userId, userInfoForm));
    }

    @Check
    @ApiOperation(value = "验证身份（1手机2邮箱3密码验证）")
    @PostMapping("/check/ident")
    public AjaxResult checkIdentity(@RequestParam("type") int type, @RequestParam("checkCode") String checkCode) {
        return userInfoService.checkPEP(type, checkCode) ? AjaxResult.success("验证成功") : AjaxResult.error("验证失败");
    }


    @Check
    @ApiOperation(value = "获取发布文章信息")
    @GetMapping("/message/blog")
    public AjaxResult getBlog() {
        String userId = AuthContextHolder.getUserId();
        List<Blog> list = blogService.selectBlogByPushId(userId);
        return AjaxResult.success(list);
    }

    @Check
    @ApiOperation(value = "获取发布活动")
    @GetMapping("/message/publish/activity")
    public AjaxResult getPublishActivity() {
        String userId = AuthContextHolder.getUserId();
        List<Activity> list = activityService.list(Wrappers.<Activity>lambdaQuery().eq(Activity::getPushId, userId));
        return AjaxResult.success(list);
    }

    @Check
    @ApiOperation(value = "获取发布竞赛")
    @GetMapping("/message/publish/contest")
    public AjaxResult getPublishContest() {
        String userId = AuthContextHolder.getUserId();
        List<Contest> list = contestService.list(Wrappers.<Contest>lambdaQuery().eq(Contest::getPushId, userId));
        return AjaxResult.success(list);
    }

    @Check
    @ApiOperation("获取报名的竞赛和活动列表," +
            "type为0查询竞赛列表，为1查询活动列表" +
            "status为0查询报名成功的竞赛列表，status为1查询待提交的报名列表")
    @GetMapping("/message/activity/{type}/{status}")
    public AjaxResult getActivity(@ApiParam("区分竞赛和活动") @PathVariable String type,
                                  @ApiParam("区分提交和未提交") @PathVariable String status) {
        String userId = AuthContextHolder.getUserId();
        return AjaxResult.success(applyService.selectListByUser(type, status, userId));
    }

//    @Check
//    @ApiOperation(value = "获取参与的活动 status 查询全部默认0")
//    @GetMapping("/message/activity/{type}/{status}")
//    public AjaxResult getActivity(@PathVariable("type") int type, @PathVariable("status") int status) {
//        String userId = AuthContextHolder.getUserId();
//        return AjaxResult.success(applyService.selectByUser(type, userId, status));
//    }

    @Check
    @ApiOperation(value = "修改重要信息（1手机2邮箱3密码）")
    @PostMapping("/edit/changeimpifm")
    public AjaxResult changeImpIfm(@RequestBody Map<String, String> map) {
        return AjaxResult.success(userInfoService.editPEP(Integer.parseInt(map.get("type")), map.get("checkCode"), map.get("change")));
    }

    @ApiOperation("测试注解功能")
    @Check(required = false)
    @GetMapping("/test1")
    public String test01() {
        return "123456" + AuthContextHolder.getUserId();
    }

    @ApiOperation("测试注解功能")
    @Check()
    @GetMapping("/test2")
    public String test02() {
        return "159753" + AuthContextHolder.getUserId();
    }

    @ApiOperation("删除发布的竞赛")
    @Check
    @DeleteMapping("/remove-contest/{id}")
    public AjaxResult removeContest(@ApiParam("竞赛id") @PathVariable String id) {
        return toAjax(contestService.removeById(id));
    }

    @ApiOperation("删除发布的活动")
    @Check
    @DeleteMapping("/remove-activity/{id}")
    public AjaxResult removeActivity(@ApiParam("活动id") @PathVariable String id) {
        return toAjax(activityService.removeById(id));
    }

    @ApiOperation("点击放弃报名，接口")
    @Check
    @DeleteMapping("/abandon-apply/{id}/{type}")
    public AjaxResult abandonApply(@ApiParam("竞赛或者活动id") @PathVariable String id,
                                   @ApiParam("类型") @PathVariable String type) {
        boolean result = this.applyService.remove(Wrappers.<Apply>lambdaQuery()
                .eq(Apply::getUserId, AuthContextHolder.getUserId())
                .eq(Apply::getActivityId, id)
                .eq(Apply::getType, type));
        return toAjax(result);
    }

    @ApiOperation("查看报名信息")
    @Check
    @GetMapping("/go-on-apply/{id}/{type}")
    public AjaxResult goOnApply(@ApiParam("竞赛或者活动id") @PathVariable String id,
                                @ApiParam("类型") @PathVariable Integer type) {
        return success(this.applyService.goOnApplyById(id, type, AuthContextHolder.getUserId()));
    }

    @ApiOperation("重新报名接口(这个接口只会删除掉当前报名的这个信息)")
    @Check
    @GetMapping("/anew-apply/{id}/{type}")
    public AjaxResult anewApply(@ApiParam("竞赛或者活动id") @PathVariable String id,
                                @ApiParam("类型") @PathVariable String type) {
        return success(this.applyService.anewApplyById(id, type, AuthContextHolder.getUserId()));
    }
}
